package com.yunze.system.card;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.mapper.mysql.YzOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信订单 消费
 * @Auther: zhang feng
 * @Date: 2021/09/02/11:55
 * @Description:
 */
@Slf4j
@Component
public class WxAddOrder {

    @Resource
    private RedisCache redisCache;
    @Resource
    private YzOrderMapper yzOrderMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 微信充值 订单 消费者
     * @param msg
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "admin_WxWebOrder_queue")
    public void createListener(String msg, Channel channel) throws IOException {
        try {
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            Map<String,Object> MsgMap = JSON.parseObject(msg);
            Map<String,Object> OrderMap = (Map<String, Object>) MsgMap.get("OrderMap");
            String ord_no = OrderMap.get("ord_no").toString();
            String iccid = OrderMap.get("iccid").toString();
            String prefix = "admin_WxWebOrder_queue";
            //执行前判断 redis 是否存在 执行数据 存在时 不执行
            Object  isExecute = redisCache.getCacheObject(prefix+":"+ord_no+":"+iccid);
            if(isExecute==null){
                redisCache.setCacheObject(prefix+":"+ord_no+":"+iccid, msg, 3, TimeUnit.SECONDS);//3 秒缓存 避免 重复消费
                AddOrder(OrderMap);//生成订单
            }
        } catch (Exception e) {
            log.error(">>错误 - 微信充值 订单  消费者:{}<<", e.getMessage());
        }
    }


    /**
     * 生成订单
     * @param OrderMap
     */
    public void AddOrder(Map<String,Object> OrderMap){
        try {
            int saveCount = orderSave(OrderMap);
            if(saveCount>0){
                log.info(">>成功 - 微信充值新增订单  受影响数据:{}<<", saveCount);
            }else{
                log.error(">>失败 - 微信充值 新增订单  受影响数据:{}<<", saveCount);
            }
        }catch (Exception e){
            log.error(">>异常 - 微信充值 AddOrder {} /n 信息 :{}<<",OrderMap,e.getMessage());
        }





    }

    /**
     * 批量新增订单时 判断是否 需要 订购达量断网  是否 开机 是否 开网 需要的整理卡号发送
     * @param map
     * @return
     */
    public int orderSave(Map<String, Object> map){
        int count = 0;
        count = yzOrderMapper.save(map);
        String status = map.get("status").toString();//支付状态 == 1 //支付成功时 触发
        if(count>0 && status.equals("1")){
            try {
                String is_dd_status = map.get("is_dd_status")!=null?map.get("is_dd_status").toString():"";
                String is_boot_status = map.get("is_boot_status")!=null?map.get("is_boot_status").toString():"";
                String is_openNet_status = map.get("is_openNet_status")!=null?map.get("is_openNet_status").toString():"";
                if(is_dd_status.equals("1") || is_boot_status.equals("1") || is_openNet_status.equals("1") ){
                    Map<String,Object> CardDiagnosisMap = new HashMap<>();
                    List<String> operationArr = new ArrayList<String>();
                    if(is_openNet_status.equals("1")){
                        operationArr.add("OpenNetwork");//开网
                    }
                    if(is_boot_status.equals("1")){
                        operationArr.add("PowerOn");//开机
                    }
                    CardDiagnosisMap.put("optionType",operationArr);
                    CardDiagnosisMap.put("iccid",map.get("iccid"));
                    Map<String, Object> updOrderMap = new HashMap<>();
                    updOrderMap.put("ord_no",map.get("ord_no"));
                    CardDiagnosisMap.put("updOrderMap", updOrderMap);
                    orderCardDiagnosisSend(CardDiagnosisMap);
                }
            }catch (Exception e){
                System.out.println("orderSave 判断是否需要 【订购达量断网】【开机】【开网】异常 "+e.getMessage());
            }
        }
        return count;
    }


    /**
     * 开机 开网 达量断网诊断发送
     * @param CardDiagnosisMap
     */
    public void orderCardDiagnosisSend(Map<String, Object> CardDiagnosisMap){
        String polling_queueName = "admin_orderCardDiagnosis_queue";
        String polling_routingKey = "admin.orderCardDiagnosis.queue";
        String polling_exchangeName = "admin_exchange";//路由
        try {
            rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(CardDiagnosisMap), message -> {
                // 设置消息过期时间 30 分钟 过期
                message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("orderCardDiagnosisSend 【订购达量断网】【开机】【开网】 指令发送异常 " + e.getMessage());
        }
    }

}
